<template>
  <el-form :model="formData" :rules="formRules" ref="formRef" size="small" :inline="false" label-width="100px">
      <el-form-item label="主题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入询价主题" maxlength="32" clearable/>
      </el-form-item>
      <el-form-item label="供应商" prop="supplierIds">
        <el-select v-model="formData.supplierIds" clearable filterable multiple style="width: 100%">
          <el-option v-for="item in supplierList" :key="item.supplierInfoId" :value="item.supplierInfoId" :label="item.shortName"/>
        </el-select>
      </el-form-item>
      <el-form-item label="要求" prop="dataItems">
        <el-table stripe border size="small" :data="formData.dataItems" :header-cell-style="{textAlign: 'center'}" :cell-style="{textAlign: 'center'}" class="product-table">
          <el-table-column label="产品名称" prop="name">
            <template v-slot="{row}">
              <el-select class="product-select" v-model="row.name" allow-create default-first-option clearable filterable>
                <el-option v-for="(item, index) in productList" :key="item.id" :value="item.name" :label="item.name" style="padding-right: 15px">
                  <span style="float: left">{{ item.name }}</span>
                  <el-button style="float: right;height: 34px" type="danger" text :icon="Delete" @click="delProductName(item, index)"/>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" prop="ver">
            <template v-slot="{row}">
              <el-input type="textarea" :rows="2" v-model="row.ver" maxlength="256" clearable/>
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="num">
            <template v-slot="{row}">
              <el-input v-model="row.num" maxlength="16" clearable/>
            </template>
          </el-table-column>
          <el-table-column label="描述/备注" prop="remark">
            <template v-slot="{row}">
              <el-input type="textarea" :rows="2" v-model="row.remark" maxlength="256" clearable/>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template v-slot="{$index}">
              <el-button text type="danger" :icon="Delete" @click="delProduct($index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" style="margin-top: 10px" :icon="Plus" @click="addProduct" size="small">添加</el-button>
      </el-form-item>
      <el-form-item label="是否公开" prop="openRes">
        <el-checkbox v-model="formData.openRes" :true-label="1" :false-label="0" size="small">公开到找资源</el-checkbox>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" :rows="3"/>
      </el-form-item>
    </el-form>
</template>

<script>
// 询价 ENQUIRY_PRICE
import {computed, reactive, ref, toRefs, onMounted, watch, nextTick} from 'vue'
import {getSupplierSelector} from '/@/api/supplier'
import {Plus, Delete} from '@element-plus/icons-vue'
import {createMatterJust} from '/@/api/matter'
import {saveProductList, getProductRecords, delProductRecord, sendEnquiryPrice} from '/@/api/supplier'
import {ElMessage} from 'element-plus'
import Cookies from 'js-cookie'
import { useCalendarConfig } from '/@/stores/calendar';
import { storeToRefs } from 'pinia';

export default {
    name: 'EnquiryPriceForm',
    emits: ['callback', 'update:code'],
    props: {
        code: {
            type: String,
            default: ''
        },
        supplierId: {   // 供应商信息id
            type: String,
            default: null
        },
        selectTime: {
            type: String,
            default: null
        },
        editId: {
          type: String,
          default: null
        }
    },
    setup(props, context) {
        const formRef = ref()
        const {code, supplierId, selectTime, editId} = toRefs(props)
        const storesCalendarConfig = useCalendarConfig();
        const { eventForm } = storeToRefs(storesCalendarConfig)
        const state = reactive({
            formData: {
                id: null,
                type: 'ENQUIRY_PRICE',
                supplierIds: [],
                dataItems: [],
                title: '询价',
                executorIds: [],
                content: '',
                openRes: 1,   // 是否公开到找资源, 0否 1是
                actionStartTime: selectTime.value,
                actionEndTime: null,
                remark: null,
                attach: '',
                attachNames: '',
                priority: 0,
                remindState: 'NONE',
                remindType: '',
            },
            formRules: {
                title: {required: true, message: '请输入询价主题', trigger: 'blur'}
            },
            supplierList: [],
            productList: [],
            getCode: false,
            originForm: {}
        })
        // 移除产品名称记录
        const delProductName = (record, index) => {
            delProductRecord(record).then(res => {
                if (res.data) {
                state.productList.splice(index, 1)
                ElMessage.success('删除成功！')
                }
            }).catch(e => console.log(e))
        }
        // 移除产品
        const delProduct = (index) => state.formData.dataItems.splice(index, 1)
        // 添加产品
        const addProduct = () => {
            if (state.formData.dataItems) {
                state.formData.dataItems.push({name: '', ver: '', num: '', remark: ''})
            } else {
                state.formData.dataItems = [{name: '', ver: '', num: '', remark: ''}]
            }
        }
        const submit = () => {
            if (!formRef) return;
            return new Promise((resolve, reject) => {
                formRef.value.validate(valid => {
                    if (!valid) {
                        return false
                    }
                    let params = JSON.parse(JSON.stringify(state.formData))
                    if (params.supplierIds && params.supplierIds.length > 0) {
                        params.supplierNames = []
                        params.supplierIds.forEach(supplierId => {
                        for (let i = 0; i < state.supplierList.length; i++) {
                            let supplier = state.supplierList[i]
                            if (supplier.supplierInfoId == supplierId) {
                                params.supplierNames.push(supplier.shortName)
                                break
                            }
                        }
                    })
                        params.supplierIds = params.supplierIds + ''
                    }
                    let productNames = []
                    if (params.dataItems && params.dataItems.length > 0) {
                        params.dataItems.forEach(item => productNames.push(item.name))
                    }
                    params.dataItems = JSON.stringify(params.dataItems)
                    if(editId.value) {
                    // 编辑
                    for(let key in params){
                        if(state.originForm.hasOwnProperty(key)){
                            state.originForm[key] = params[key]
                        }
                        if(state.originForm.info.hasOwnProperty(key)){
                            state.originForm.info[key] = params[key]
                        }
                        }
                        storesCalendarConfig.setEventForm(state.originForm)
                        reset()
                        resolve('edit') 
                    }else{
                        createMatterJust(params).then(res => {
                            if (res.data) {
                                // 提交产品列表名称记录
                                if (productNames.length > 0) {
                                    saveProductList(productNames).catch(e => console.log(e))
                                }
                                if (params.supplierIds && params.supplierIds.length > 0) {
                                    sendEnquiryPrice(params).catch(e => console.log(e))
                                }
                                ElMessage.success('提交成功！')
                                reset()
                                resolve()
                            }else{
                                reject()
                            }
                        }).catch(e => reject(e))
                    }
                })
            })
        }
        const reset = () => {
            if (!formRef) return;
            formRef.value.resetFields();
            context.emit('update:code', '')
        }
        const checkCode = computed(() => {
            let flag = code.value == state.formData.type
            if (flag) {
              if (supplierId.value) {
                state.formData.supplierIds = [supplierId.value]
              }
              state.formData.executorIds.push(Cookies.get('userId'))
              // 获取供应商列表
              getSupplierSelector().then(res => state.supplierList = res.data).catch(e => console.log(e))
              // 获取供应商产品列表
              getProductRecords().then(res => state.productList = res.data).catch(e => console.log(e))
            }
            return flag
        })
        watch(() => eventForm.value,
          val => {
            if(editId.value && val) {
              // 编辑
              nextTick(() => {
                const data = val
                if(!data) return
                state.originForm = data
                for(let params in data.info){
                  // 拿出info里面的数据
                  if(state.formData.hasOwnProperty(params)) {
                    state.formData[params] = data.info[params]
                  }
                }
                for(let key in data) {
                  // 列表里面的数据
                  if(state.formData.hasOwnProperty(key)) {
                    state.formData[key]= data[key]
                  }
                }
                if(data.remindType){
                  state.formData.remindType = data.remindType.split(',')
                }
                state.selfId = Cookies.get('userId')
                state.formData.executorIds[0] = state.selfId
                if(data.executorIds){
                  state.formData.executorIds.concat(data.executorIds)
                }
                if(data.info && data.info.dataItems) {
                    state.formData.dataItems = JSON.parse(data.info.dataItems)
                }
                if(data.info && data.info.supplierIds) {
                    state.formData.supplierIds = data.info.supplierIds.split(',')
                }
              })
            }
          }        
        )
        onMounted(() => {
            state.getCode = checkCode.value
        })
        return {
            ...toRefs(state),
            submit,
            reset,
            Plus,
            Delete,
            formRef,
            delProductName,
            delProduct,
            addProduct
        }
    }
}
</script>

<style>

</style>